<template>
  <div>
    <ContentHeader title="BANNER管理">
      <template #title>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          添加BANNER
        </el-button>
      </template>
    </ContentHeader>
    <ContentBody v-loading="store.loading">
      <el-table :data="store.banners" :stripe="true" :highlight-current-row="true">
        <el-table-column property="id" width="80" />
        <el-table-column property="title" label="标题" />
        <el-table-column property="cover" label="BANNER">
          <template #default="scope">
            <el-image :src="cfg.imageUrl(scope.row.cover)" fit="contain" />
          </template>
        </el-table-column>
        <el-table-column property="link" label="链接">
          <template #default="scope">
            <el-link :href="scope.row.link" target="_blank">{{ scope.row.link }}</el-link>
          </template>
        </el-table-column>
        <el-table-column property="onself" label="上/下架">
          <template #default="scope">
            <el-switch v-model="scope.row.onself" @change="handleOnself" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button plain @click="handleUpdate(scope.row)">
              <el-icon><Edit /></el-icon>
              修改
            </el-button>
            <el-button plain @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentBody>
    <RouterView />
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useBannerStore } from '@/stores/banner'
import cfg from '@/config/config'

const store = useBannerStore()
const router = useRouter()

const handleCreate = () => {
  router.push({ name: 'center_banner_create' })
}
const handleUpdate = (row: any) => {
  router.push({ name: 'center_banner_update', params: { id: row.id } })
}
const handleOnself = (val: boolean) => {
  store.updateOnself(val)
}
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除' + row.title + '吗?', '确定删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    const result = await store.deleteBanner(row.id)
    if (result) {
      ElMessage.success('删除成功')
      store.loadBanners()
    }
  })
}

onMounted(() => {
  store.loadBanners()
})
</script>
